//: net/mindview/util/TextFile.java
// Static functions for reading and writing text files as
// a single string, and treating a file as an ArrayList.
package com.alibaba.wallstreet.uitls;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;

public class TextFileUtil extends ArrayList<String> {

    /**
     * 
     */
    private static final long serialVersionUID = 4203085321762550670L;

    // Read a file as a single string:
    public static String read(String fileName, String cs) {
        StringBuilder sb = new StringBuilder();
        try {
            File f = new File(fileName).getAbsoluteFile();
            InputStreamReader read = new InputStreamReader(new FileInputStream(f), cs);
            BufferedReader reader = new BufferedReader(read);
            try {
                String s;
                while ((s = reader.readLine()) != null) {
                    sb.append(s);
                    sb.append("\n");
                }
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    // Write a single file in one method call:
    public static void write(String fileName, String text, String cs) {
        try {
            PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile(), cs);
            try {
                out.print(text);
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // Read a file, split by any regular expression:
    public TextFileUtil(String fileName, String splitter){
        super(Arrays.asList(read(fileName, System.getProperty("file.encoding")).split(splitter)));
        if (get(0).equals("")) remove(0);
    }

    // Normally read by lines:
    public TextFileUtil(String fileName){
        this(fileName, "\n");
    }

    public TextFileUtil(){
    }

    public void write(String fileName, String cs) {
        try {
            PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile(), cs);
            try {
                for (String item : this)
                    out.println(item);
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getFilePathInClasspath(String classpathDes) {
        return new File(Thread.currentThread().getContextClassLoader().getResource(classpathDes).getFile()).getPath();
    }

}
